<template>
  <div class="container">
    <el-header class="header">
      <el-button class="back" @click="goBack">
        <el-icon>
          <ArrowLeft />
        </el-icon>
      </el-button>
      <span class="title">消息</span>
    </el-header>

    <el-main class="main-content">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="sortedMessages.length" class="messages-container">
        <div v-for="message in sortedMessages" :key="message.id">
          <div class="message-time">{{ message.sendTime }}</div>
          <div class="message-item">
            <div class="notice-title-wrapper">
              <div class="notice-title-text">
                {{ message.adminId ? '职位调动通知' : '审批通知' }}
              </div>
              <el-button type="primary" class="confirm-btn" @click="confirmRead(message.id)"
                :disabled="message.isRead === 1" style="width: 70px;">
                {{ message.isRead === 1 ? '已确认' : '确认已读' }}
              </el-button>
            </div>

            <div class="notice-content-box">
              <pre class="notice-content">{{ message.content }}</pre>
            </div>
            <div class="notice-footer">
              <div class="notice-meta">
                <div class="notice-dept">发送人：{{ message.adminId ? senders[message.adminId] :
                  empSenders[message.leaderId] }}</div>
              </div>
              <div class="check" @click="goToCheckMessage(message.id)">
                查看详情
              </div>
            </div>
          </div>

        </div>
      </div>
      <div v-else class="no-data">暂无消息</div>
    </el-main>
  </div>
</template>

<script>
import { markAsRead, getMessageByEmpId } from "../../api/message.js";
import { getAdminNameById } from "../../api/admin.js";
import { getSessionStorageObj } from "../../utils/common.js";
import { getEmpNameById } from "../../api/basedata.js";

//得到全局数据
let userInfo = getSessionStorageObj('userInfo');
console.log('用户信息:', userInfo);

export default {
  data() {
    return {
      empId: userInfo.empId,
      loading: false,
      messages: [],//存储该员工所有消息
      senders: {},// 缓存管理员姓名
      empSenders: {}, // 存储员工姓名
    };
  },
  computed: {
    sortedMessages() {
      // 按时间倒序排列
      return [...this.messages].sort((a, b) =>
        new Date(b.sendTime) - new Date(a.sendTime)
      )
    },
    senderName: {
      get(senderId) {
        return this.getSenderName(senderId);
      }
    },
  },
  methods: {
    goBack() {
      this.$router.push("/betch");
    },

    goToCheckMessage(messageId) {
      this.$router.push({ path: `/checkMessage/${messageId}` });
    },

    // 获取员工姓名的方法
    async getEmpSenderName(empId) {
      if (this.empSenders[empId]) {
        return this.empSenders[empId];
      }
      try {
        const res = await getEmpNameById({ id: empId });
        this.empSenders[empId] = res.flag ? res.result : "未知发送人";
        return this.empSenders[empId];
      } catch (error) {
        console.error("获取发送人信息失败:", error);
        this.empSenders[empId] = "未知发送人";
        return "未知发送人";
      }
    },

    // api-获取发送人姓名
    async getSenderName(senderId) {
      // 检查缓存中是否已有发送人信息
      if (this.senders[senderId]) {
        return this.senders[senderId];
      }
      try {
        const res = await getAdminNameById({ id: senderId });
        this.senders[senderId] = res.flag ? res.result : "未知管理员";
        return this.senders[senderId];
      } catch (error) {
        console.error("获取发送人信息失败:", error);
        this.senders[senderId] = "未知管理员";
        return "未知管理员";
      }
    },

    // api-确认已读
    async confirmRead(messageId) {
      try {
        const res = await markAsRead({ id: messageId });
        if (res.flag && this.messages) {
          const message = this.messages.find(msg => msg.id === messageId);
          if (message) {
            message.isRead = 1;
          }
        }
      } catch (error) {
        console.error("标记已读失败:", error);
      }
    },

    // api-获取消息列表
    async fetchMessage() {
      this.loading = true;
      try {
        const res = await getMessageByEmpId({ id: this.empId });

        // 成功响应且result是数组（包括空数组）
        if (res.flag && Array.isArray(res.result)) {
          this.messages = res.result;

          // 预加载发送人姓名（只有当有消息时才执行）
          if (this.messages.length > 0) {
            await Promise.all(
              this.messages.map((msg) =>
                msg.adminId
                  ? this.getSenderName(msg.adminId)
                  : this.getEmpSenderName(msg.leaderId)
              )
            );
          }
        }
        // 成功响应但result为null/undefined（视为无消息）
        else if (res.flag && (res.result === null || res.result === undefined)) {
          this.messages = []; // 静默处理，不报警告
        }
        // 其他失败情况
        else {
          console.warn('获取消息失败:', res.reason);
          this.messages = [];
        }
      } catch (error) {
        console.error("获取消息详情失败:", error);
        this.messages = [];
      } finally {
        this.loading = false;
      }
    }
  },
  mounted() {
    this.fetchMessage();
  },
}
</script>

<style scoped>
.container {
  height: 100vh;
  width: 100vw;
  background-color: #e1efff;
  overflow-x: hidden;
  position: relative;
}

.header {
  height: 8vh;
  width: 100%;
  background-color: white;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
}

.main-content {
  margin-top: 15px;
  padding-top: 8vh;
  overflow-y: auto;
}

.back {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  border: none;
  font-size: 24px;
  background: transparent;
}

.messages-container {
  display: flex;
  flex-direction: column;
}

.message-time {
  color: #999;
  font-size: 14px;
  text-align: center;
}

.message-item {
  background-color: white;
  /* margin: 20px; */
  margin: 8px 20px 20px;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.notice-title-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* 确保垂直居中 */
  margin-bottom: 16px;
}

.notice-title-text {
  color: #1a1a1a;
  font-size: 16px;
  font-weight: bold;
  margin: 0;
}

.confirm-btn {
  /* float: right; */
  width: 70px;
  margin: 0;
  /* 移除默认边距 */
  /* 如果按钮高度不一致，可以设置固定高度 */
  height: 32px;
  /* 根据设计调整 */
  line-height: 32px;
  /* 保持文字垂直居中 */
}

.notice-content-box {
  padding: 5px 5px;
  margin-bottom: 5px;
  border-top: 1px solid #f0f0f0;
}

.notice-content {
  font-size: 16px;
  line-height: 1.5;
  color: #333;
  /* white-space: pre-wrap; */
  /* word-wrap: break-word; */
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  margin: 0;
  /* 新增以下属性实现两行省略 */
  display: -webkit-box;
  -webkit-line-clamp: 2;
  /* 限制显示行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  /* 改为normal */
  word-wrap: break-word;
  max-height: 3em;
}

.notice-footer {
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.notice-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.notice-dept {
  color: #409eff;
  font-weight: 500;
}

.notice-time {
  color: #999;
}

.loading,
.no-data {
  text-align: center;
  padding: 50px;
  color: #909399;
  font-size: 16px;
}

/* 保留原有所有样式，新增以下样式 */
.notice-footer {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.notice-meta {
  flex-grow: 1;
}

.check {
  color: #909399;
  /* 设置字体颜色为灰色 */
  cursor: pointer;
  /* 设置鼠标悬停时的样式 */
  text-decoration: underline;
  /* 添加下划线 */
}
</style>